package com.fly.dbexample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.fly.db.dao.DaoFactory;
import com.fly.db.exception.DBDaoInitException;
import com.fly.dbexample.bean.User;
import com.fly.dbexample.dao.UserDao;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    UserDao userDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button save = (Button) findViewById(R.id.id_save_btn);
        Button read = (Button) findViewById(R.id.id_read_btn);
        Button deleteAll = (Button) findViewById(R.id.id_delete_btn);

        save.setOnClickListener(this);
        read.setOnClickListener(this);
        deleteAll.setOnClickListener(this);

        try {
            userDao = (UserDao) DaoFactory.getInstance().getDao(UserDao.class, "user");
        } catch (DBDaoInitException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.id_save_btn:
                saveUser();
                break;
            case R.id.id_read_btn:
                readUser();
                break;
            case R.id.id_delete_btn:
                deleteUser();
                break;
        }
    }

    private void deleteUser() {
        userDao.delete();
    }

    private void readUser() {
        ArrayList<User> users = userDao.read();
        if (users == null) {
            return;
        }
        for (User user:
             users) {
            Log.e("tag", user.getName() + "-" + user.getAge());
        }
    }
int i = 0;
    private void saveUser() {

        User user = new User();
        user.setName("哈哈" + (i++));
        user.setAge(24+i);
        userDao.save(user);
    }
}
